#pragma once
#include <iostream>
#include <queue>
#include <functional>
#include <string>
#include <pthread.h>
#include <time.h>
#include <stdlib.h>
#include <unistd.h>
#define max_size 5

template<class Task>
class blockqueue
{
public:
    blockqueue()
    : _max_size (max_size) 
    {
        pthread_mutex_init(&_mtx,  nullptr);
        pthread_cond_init(&_pcond, nullptr);
        pthread_cond_init(&_ccond, nullptr);
    }


    bool push(const Task& task)
    {
        pthread_mutex_lock(&_mtx);
        while(isfull())
        {
            pthread_cond_wait(&_pcond, &_mtx);
        }
        _qt.push(task);
        pthread_mutex_unlock(&_mtx);
        pthread_cond_signal(&_ccond);
        return true;
    }

    
    bool pop(Task* task)
    {
        pthread_mutex_lock(&_mtx);
        while(isempty())
        {
            pthread_cond_wait(&_ccond, &_mtx);
        }
        *task = _qt.front();
        _qt.pop();
        pthread_mutex_unlock(&_mtx);
        pthread_cond_signal(&_pcond);
        return true;
    }

    bool isempty()
    {
        return _qt.empty();
    }

    bool isfull()
    {
        return _qt.size() == _max_size;
    }

    ~blockqueue()
    {
        pthread_mutex_destroy(&_mtx);
        pthread_cond_destroy(&_pcond);
        pthread_cond_destroy(&_ccond);
    }
private:
    std::queue<Task> _qt;
    size_t _max_size;
    pthread_mutex_t _mtx;
    pthread_cond_t _pcond;
    pthread_cond_t _ccond;
};